package com.demo.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author wzm
 * @create 2023-06-26 11:15
 */
public class BaseServlet extends HttpServlet {
    //当访问子类servlet时 子类没有service 会执行到这里  则这里 可以想办法调用当前请求要执行方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //根据请求路径调用方法  xxxx/xxx/web05/dog/add  add

        //1.获取请求的路径
        String uri = req.getRequestURI();//    /web05/dog/add
      
        //2.截取最后一个斜杆后的单词作为方法名
        String methodName = uri.substring(uri.lastIndexOf('/') + 1);
        System.out.println("methodName = " + methodName);//add
        
        //3.调用方法
        //调用方法的对象 反射
        Class<? extends BaseServlet> cla = this.getClass();

        try {
            //获取方法
            Method method = cla.getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.setAccessible(true);//设置临时访问

            //通过当前子类的字节码文件调用方法
            method.invoke(this,req,resp);

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}
